package com.bancomer.batch.converters;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import com.bancomer.batch.Constants;
import com.bancomer.batch.MapConstants;
import com.bancomer.batch.converters.impl.AuditAlertImpl;
import com.bancomer.batch.pojo.Alert;
import com.bancomer.batch.pojo.Detail;
import com.bancomer.batch.pojo.FileHelper;
import com.bancomer.batch.pojo.Summary;
import com.bancomer.batch.util.NumberComparator;
import com.bancomer.batch.util.StringConverter;
import com.blackbear.flatworm.ConfigurationReader;
import com.blackbear.flatworm.FileFormat;
import com.blackbear.flatworm.MatchedRecord;

public class FileToObjectsConverter {
	
	public static AuditAlert getObjectsFromSummary(Alert alert) throws Exception{
		AuditAlert auditAlert = new AuditAlertImpl();
		final Properties alertConstants = MapConstants.getInstance(alert.getProperties().getProperty("constantsFile")).getConstants();
		FileHelper summaryFileScript = null;
		for(FileHelper output : alert.getPigScript().getOutputResultsFiles()){
			if(output.getProperties()!=null&&!output.getProperties().isEmpty()){
				if(output.getProperties().getProperty("outputType").equals(alertConstants.getProperty("OUTPUT_TYPE_SUMMARY"))){
					summaryFileScript = output;
					break;
				}
			}
		}
		summaryFileScript.setName(StringConverter.convertPatternToDate(summaryFileScript.getName()));
		auditAlert = FlatWormReader.readSummary(alertConstants, summaryFileScript);
		for(Summary summary: auditAlert.getSummary()){
               SimpleDateFormat format = new SimpleDateFormat(alertConstants.getProperty("AUDIT_PATTERN_DATE"));
   			   SimpleDateFormat formatFile = new SimpleDateFormat((Constants.formatDate)==null?"yyMMdd":Constants.formatDate);
               if("".equals(summary.getFecMuestra())){
					if(Constants.alertDate==null||"".equals(Constants.alertDate)){
						summary.setFecMuestra(format.format(new Date()));
					}
					else{
						Date date = formatFile.parse(Constants.alertDate);
						summary.setFecMuestra(format.format(date));
					}
				}
				else{
					summary.setFecMuestra(format.format(summary.getFecMuestra()));
				}
                double amount = Double.parseDouble(summary.getQtyRiesInh());
   				DecimalFormat df = new DecimalFormat(alertConstants.getProperty("DECIMAL_FORMAT"));
   				summary.setQtyRiesInh(df.format(amount));
   				summary.setFecDatos(summary.getFecMuestra());
        }
		return auditAlert;
	}
	public static AuditAlert getObjectsFromDetail(Alert alert) throws Exception{
		AuditAlert auditAlert = new AuditAlertImpl();
		final Properties alertConstants = MapConstants.getInstance(alert.getProperties().getProperty("constantsFile")).getConstants();
		FileHelper detailFileScript = null;
		String contrato = "";
		int contador=0;
		for(FileHelper output : alert.getPigScript().getOutputResultsFiles()){
			if(output.getProperties()!=null&&!output.getProperties().isEmpty()){
				if(output.getProperties().getProperty("outputType").equals(alertConstants.getProperty("OUTPUT_TYPE_DETAIL"))){
					detailFileScript = output;
					break;
				}
			}
		}
		detailFileScript.setName(StringConverter.convertPatternToDate(detailFileScript.getName()));
		auditAlert = FlatWormReader.readDetail(alertConstants, detailFileScript);
		for(Detail detail: auditAlert.getDetail()){
               SimpleDateFormat format = new SimpleDateFormat(alertConstants.getProperty("AUDIT_PATTERN_DATE"));
   			   SimpleDateFormat formatFile = new SimpleDateFormat((Constants.formatDate)==null?"yyMMdd":Constants.formatDate);
               if("".equals(detail.getFecMuestra())){
					if(Constants.alertDate==null||"".equals(Constants.alertDate)){
						detail.setFecMuestra(format.format(new Date()));
					}
					else{
						Date date = formatFile.parse(Constants.alertDate);
						detail.setFecMuestra(format.format(date));
					}
				}
				else{
					detail.setFecMuestra(format.format(detail.getFecMuestra()));
				}
	   			if("".equals(detail.getCodOperale())){
	   				if(contrato.equals("")){
	   					contrato = detail.getCodContaler();
	   					contador = 1;
	   				}
	   				else if(contrato.equals(detail.getCodContaler())){
	   					contador++;
	   				}
	   				else if(!contrato.equals(detail.getCodContaler())){
	   					contador = 1;
	   					contrato = detail.getCodContaler();
	   				}
	   				detail.setCodOperale(String.valueOf(contador));
	   			}
                double amount = Double.parseDouble(detail.getQtyToTimp());
   				DecimalFormat df = new DecimalFormat(alertConstants.getProperty("DECIMAL_FORMAT"));
   				detail.setQtyToTimp(df.format(amount));
        }
		return auditAlert;
	}
	/*
	public static AuditAlert getObjectsFromSummary(Alert alert) throws Exception{
		MapConstants mapConstants = MapConstants.getInstance(alert.getProperties().getProperty("constantsFile"));
		final Properties alertConstants = mapConstants.getConstants();
		FileReader summaryFile = null;
		BufferedReader buffer = null;
		AuditAlert auditAlert = new AuditAlertImpl();
		String line = "";
		for(FileHelper output : alert.getPigScript().getOutputResultsFiles()){
			if(output.getProperties()!=null&&!output.getProperties().isEmpty()){
				if(output.getProperties().getProperty("outputType").equals(alertConstants.getProperty("OUTPUT_TYPE_SUMMARY"))){
						summaryFile= new FileReader(output.getLocalPath()+output.getName()+"/part-r-00000");
						buffer = new BufferedReader(summaryFile);
						break;
				}
			}
		}
		if(buffer == null){
			throw new Exception("No se encontró el archivo de resumen");
		}
		line = buffer.readLine();
		while(line!=null){
			String [] columns = line.split(alertConstants.getProperty("HADOOP_SEPARATOR_FILE"));
			Summary summaryObject = new Summary();
			summaryObject.setName(columns[Integer.parseInt(alertConstants.getProperty("NAME"))]);
			SimpleDateFormat format = new SimpleDateFormat(alertConstants.getProperty("AUDIT_PATTERN_DATE"));
			SimpleDateFormat formatFile = new SimpleDateFormat((Constants.formatDate)==null?"yyMMdd":Constants.formatDate);
			if(NumberComparator.compareLength(alertConstants.getProperty("FEC_MUESTRA"),columns.length-1)==columns.length-1){
				summaryObject.setFecMuestra("");
			}
			else{
				if("".equals(columns[Integer.parseInt(alertConstants.getProperty("FEC_MUESTRA"))])){
					if(Constants.alertDate==null||"".equals(Constants.alertDate)){
						summaryObject.setFecMuestra(format.format(new Date()));
					}
					else{
						Date date = formatFile.parse(Constants.alertDate);
						summaryObject.setFecMuestra(format.format(date));
					}
				}
				else{
					summaryObject.setFecMuestra(format.format(columns[Integer.parseInt(alertConstants.getProperty("FEC_MUESTRA"))]));
				}
			}
			if(NumberComparator.compareLength(alertConstants.getProperty("COD_PAISBBV"), columns.length-1)==columns.length-1){
				summaryObject.setCodPaisBbv("");
			}
			else{
				summaryObject.setCodPaisBbv(columns[Integer.parseInt(alertConstants.getProperty("COD_PAISBBV"))]);
			}
			if(NumberComparator.compareLength(alertConstants.getProperty("COD_ENTIALFA"), columns.length-1)==columns.length-1){
				summaryObject.setCodEntiAlfa("");
			}
			else{
				summaryObject.setCodEntiAlfa(columns[Integer.parseInt(alertConstants.getProperty("COD_ENTIALFA"))]);
			}
			if(NumberComparator.compareLength(alertConstants.getProperty("COD_OFICINA"), columns.length-1)==columns.length-1){
				summaryObject.setCodOficina("");
			}
			else{
				summaryObject.setCodOficina(columns[Integer.parseInt(alertConstants.getProperty("COD_OFICINA"))]);
			}
			if(NumberComparator.compareLength(alertConstants.getProperty("COD_CLIENIF"), columns.length-1)==columns.length-1){
				summaryObject.setCodClieNif("");
			}
			else{
				summaryObject.setCodClieNif(columns[Integer.parseInt(alertConstants.getProperty("COD_CLIENIF"))]);
			}
			summaryObject.setCodClieNif(columns[NumberComparator.compareLength(alertConstants.getProperty("COD_CLIENIF"), columns.length-1)]);
			summaryObject.setCodAlerta(columns[NumberComparator.compareLength(alertConstants.getProperty("COD_ALERTA"), columns.length-1)]);
			summaryObject.setCodContaler(columns[NumberComparator.compareLength(alertConstants.getProperty("COD_CONTALER"), columns.length-1)]);
			summaryObject.setCodTerritOf(columns[NumberComparator.compareLength(alertConstants.getProperty("COD_TERRITOF"), columns.length-1)]);
			summaryObject.setCodCdug(columns[NumberComparator.compareLength(alertConstants.getProperty("COD_CDUG"), columns.length-1)]);
			summaryObject.setCodCdar(columns[NumberComparator.compareLength(alertConstants.getProperty("COD_CDAR"), columns.length-1)]);
			summaryObject.setCodNif(columns[NumberComparator.compareLength(alertConstants.getProperty("COD_NIF"), columns.length-1)]);
			summaryObject.setDesNomClie(columns[NumberComparator.compareLength(alertConstants.getProperty("DES_NOMCLIE"), columns.length-1)]);
			summaryObject.setQtyNumCtos(columns[NumberComparator.compareLength(alertConstants.getProperty("QTY_NUMCTOS"), columns.length-1)]);
			summaryObject.setQtyNumOper(columns[NumberComparator.compareLength(alertConstants.getProperty("QTY_NUMOPER"), columns.length-1)]);
			
			double amount = Double.parseDouble(columns[NumberComparator.compareLength(alertConstants.getProperty("QTY_RIESINH"), columns.length-1)]);
			DecimalFormat df = new DecimalFormat(alertConstants.getProperty("DECIMAL_FORMAT"));
			summaryObject.setQtyRiesInh(df.format(amount));
			summaryObject.setQtyPorcent(columns[NumberComparator.compareLength(alertConstants.getProperty("QTY_PORCENT"), columns.length-1)]);
			summaryObject.setQtyImporte1(columns[NumberComparator.compareLength(alertConstants.getProperty("QTY_IMPORTE1"), columns.length-1)]);
			summaryObject.setQtyImporte2(columns[NumberComparator.compareLength(alertConstants.getProperty("QTY_IMPORTE2"), columns.length-1)]);
			summaryObject.setQtyImporte3(columns[NumberComparator.compareLength(alertConstants.getProperty("QTY_IMPORTE3"), columns.length-1)]);
			summaryObject.setQtyNumero1(columns[NumberComparator.compareLength(alertConstants.getProperty("QTY_NUMERO1"), columns.length-1)]);
			summaryObject.setCodUsualer(columns[NumberComparator.compareLength(alertConstants.getProperty("COD_USUALER"), columns.length-1)]);
			summaryObject.setCodAlerconc(columns[NumberComparator.compareLength(alertConstants.getProperty("COD_ALERCONC"), columns.length-1)]);
			//summaryObject.setXtiEstmues(columns[NumberComparator.compareLength(alertConstants.getProperty("XTI_ESTMUES"), columns.length-1)]);
			summaryObject.setFecDatos(summaryObject.getFecMuestra());
			summaryObject.setCodSiginh(columns[NumberComparator.compareLength(alertConstants.getProperty("COD_SIGINH"), columns.length-1)]);
			summaryObject.setDesFvencim(columns[NumberComparator.compareLength(alertConstants.getProperty("DES_FVENCIM"), columns.length-1)]);
			summaryObject.setDesFvalr(columns[NumberComparator.compareLength(alertConstants.getProperty("DES_FVALR"), columns.length-1)]);
			auditAlert.addSummary(summaryObject);
			line = buffer.readLine();
		}
		buffer.close();
		return auditAlert;
	}
	*/
/*	public static AuditAlert getObjectsFromDetail(Alert alert) throws Exception{
		MapConstants mapConstants = MapConstants.getInstance(alert.getProperties().getProperty("constantsFile"));
		final Properties alertConstants = mapConstants.getConstants();
		FileReader detailFile = null;
		BufferedReader buffer = null;
		AuditAlert auditAlert = new AuditAlertImpl();
		String line = "";
		String contrato = "";
		int contador=0;
		for(FileHelper output : alert.getPigScript().getOutputResultsFiles()){
			if(output.getProperties()!=null&&!output.getProperties().isEmpty()){
				if(output.getProperties().getProperty("outputType").equals(alertConstants.getProperty("OUTPUT_TYPE_DETAIL"))){
					detailFile= new FileReader(output.getLocalPath()+output.getName()+"/part-r-00000");
					buffer = new BufferedReader(detailFile);
					break;
				}
					
			}
		}
		if(buffer == null){
			throw new Exception("No se encontró el archivo de desglose");
		}
		line = buffer.readLine();
		while(line!=null){
			String [] columns = line.split(alertConstants.getProperty("HADOOP_SEPARATOR_FILE"));
			Detail detailObject = new Detail();
			detailObject.setName(columns[Integer.parseInt(alertConstants.getProperty("NAME"))]);
			SimpleDateFormat format = new SimpleDateFormat(alertConstants.getProperty("AUDIT_PATTERN_DATE"));
			SimpleDateFormat formatFile = new SimpleDateFormat((Constants.formatDate)==null?"yyMMdd":Constants.formatDate);
			if("".equals(columns[NumberComparator.compareLength(alertConstants.getProperty("FEC_MUESTRA"),columns.length-1)])){
				if(Constants.alertDate==null||"".equals(Constants.alertDate)){
					detailObject.setFecMuestra(format.format(new Date()));
				}
				else{
					Date date = formatFile.parse(Constants.alertDate);
					detailObject.setFecMuestra(format.format(date));
				}
			}
			else{
				
				detailObject.setFecMuestra(format.format(columns[NumberComparator.compareLength(alertConstants.getProperty("FEC_MUESTRA"),columns.length-1)]));
			}
			detailObject.setCodPaisBbv(columns[NumberComparator.compareLength(alertConstants.getProperty("COD_PAISBBV"), columns.length-1)]);
			detailObject.setCodEntiAlfa(columns[NumberComparator.compareLength(alertConstants.getProperty("COD_ENTIALFA"), columns.length-1)]);
			detailObject.setCodOficina(columns[NumberComparator.compareLength(alertConstants.getProperty("COD_OFICINA"), columns.length-1)]);
			detailObject.setCodClieNif(columns[NumberComparator.compareLength(alertConstants.getProperty("COD_CLIENIF"), columns.length-1)]);
			detailObject.setCodAlerta(columns[NumberComparator.compareLength(alertConstants.getProperty("COD_ALERTA"), columns.length-1)]);
			
			int contalerIndex = NumberComparator.compareLength(alertConstants.getProperty("COD_CONTALER"), columns.length-1);
			detailObject.setCodContaler(columns[contalerIndex]);
			int operaleIndex = NumberComparator.compareLength(alertConstants.getProperty("COD_OPERALE"), columns.length-1);
			if("".equals(columns[operaleIndex])){
				if(contrato.equals("")){
					contrato = columns[contalerIndex];
					contador = 1;
				}
				else if(contrato.equals(columns[contalerIndex])){
					contador++;
				}
				else if(!contrato.equals(columns[contalerIndex])){
					contador = 1;
					contrato = columns[contalerIndex];
				}
				detailObject.setCodOperale(String.valueOf(contador));
			}
			else{
				detailObject.setCodOperale(columns[operaleIndex]);
			}
			double amount = Double.parseDouble(columns[NumberComparator.compareLength(alertConstants.getProperty("QTY_TOTIMP"), columns.length-1)]);
			DecimalFormat df = new DecimalFormat(alertConstants.getProperty("DECIMAL_FORMAT"));
			detailObject.setQtyToTimp(df.format(amount));
			detailObject.setFecContr(columns[NumberComparator.compareLength(alertConstants.getProperty("FEC_CONTR"), columns.length-1)]);
			
			auditAlert.addDetail(detailObject);
			line = buffer.readLine();
		}
		buffer.close();
		return auditAlert;
	}*/
	/*
	public static List<Detail> getObjectsFromDetail(String text) throws Exception{
		List<Detail> detailObjects = new ArrayList<Detail>();
		FileReader detailFile = null;
		BufferedReader buffer = null;
		String [] line = null;
		String contrato = "";
		int contador=0;
		//line = buffer.readLine();
		line = text.split("\n");
		for(int i = 0; i<line.length;i++){
			String [] columns = line[i].split("\t");
			Detail detailObject = new Detail();
			detailObject.setName(columns[Integer.parseInt(alertConstants.getProperty("NAME"))]);
			SimpleDateFormat format = new SimpleDateFormat(Constants.AUDIT_PATTERN_DATE);
			if("".equals(columns[Integer.parseInt(alertConstants.getProperty("FEC_MUESTRA"))])){
				if(Constants.alertDate==null||"".equals(Constants.alertDate)){
					detailObject.setFecMuestra(format.format(new Date()));
				}
				else{
					detailObject.setFecMuestra(format.format(format.parse(Constants.alertDate)));
				}
			}
			else{
				
				detailObject.setFecMuestra(format.format(columns[Integer.parseInt(alertConstants.getProperty("FEC_MUESTRA]));
			}
			detailObject.setCodPaisBbv(columns[Integer.parseInt(alertConstants.getProperty("COD_PAISBBV"))]);
			detailObject.setCodEntiAlfa(columns[Integer.parseInt(alertConstants.getProperty("COD_ENTIALFA"))]);
			detailObject.setCodOficina(columns[Integer.parseInt(alertConstants.getProperty("COD_OFICINA"))]);
			detailObject.setCodClieNif(columns[Integer.parseInt(alertConstants.getProperty("COD_CLIENIF"))]);
			detailObject.setCodAlerta(columns[Integer.parseInt(alertConstants.getProperty("COD_ALERTA"))]);
			detailObject.setCodContaler(columns[Integer.parseInt(alertConstants.getProperty("COD_CONTALER"))]);

			if("".equals(columns[Integer.parseInt(alertConstants.getProperty("COD_OPERALE"))])){
				if(contrato.equals("")){
					contrato = columns[Integer.parseInt(alertConstants.getProperty("COD_CONTALER];
					contador = 1;
				}
				else if(contrato.equals(columns[Integer.parseInt(alertConstants.getProperty("COD_CONTALER"))])){
					contador++;
				}
				else if(!contrato.equals(columns[Integer.parseInt(alertConstants.getProperty("COD_CONTALER"))])){
					contador = 1;
					contrato = columns[Integer.parseInt(alertConstants.getProperty("COD_CONTALER];
				}
				detailObject.setCodOperale(String.valueOf(contador));
			}
			else{
				detailObject.setCodOperale(columns[Integer.parseInt(alertConstants.getProperty("COD_OPERALE"))]);
			}
			detailObject.setQtyToTimp(columns[Integer.parseInt(alertConstants.getProperty("QTY_TOTIMP"))]);
			detailObject.setFecContr(columns[Integer.parseInt(alertConstants.getProperty("FEC_CONTR"))]);
			
			detailObjects.add(detailObject);
		}
		
		return detailObjects;
	}
	public static void main(String ... args) throws Exception{
		String archivo = "TSALAYCN		0412	0074	0404	A0000068	FRAU-INT-006	007404044447110990		250001.00	2014-04-28\n"+
				"TSALAYCN		0412	0074	0007	A0000085	FRAU-INT-006	007400072300626791		100000.00	2014-04-28\n"+
				"TSALAYCN		0412	0074	0007	A0000085	FRAU-INT-006	007400072300626791		100000.00	2014-04-28\n"+
				"TSALAYCN		0412	0074	0007	A0000085	FRAU-INT-006	007400072300626791		90000.00	2014-04-28\n"+
				"TSALAYCN		0412	0074	0007	A0000126	FRAU-INT-006	007400072028083223		34152.00	2014-04-28\n"+
				"TSALAYCN		0412	0074	0007	A0000126	FRAU-INT-006	007400072028083223		1921.00	2014-04-28\n"+
				"TSALAYCN		0412	0074	0007	A0000126	FRAU-INT-006	007400072028083223		520152.00	2014-04-28\n"+
				"TSALAYCN		0412	0074	0007	A0000117	FRAU-INT-006	007400071452387239		920172.00	2014-04-28\n"+
				"TSALAYCN		0412	0074	0007	A0000117	FRAU-INT-006	007400071452387239		420152.00	2014-04-28\n"+
				"TSALAYCN		0412	0074	0007	A0000123	FRAU-INT-006	007400071357137877		480152.00	2014-04-28\n";
		List<Detail> detalles = getObjectsFromDetail(archivo);
		for(Detail detalle:detalles){
			System.out.println(detalle.getName()+"\t"+detalle.getFecMuestra()+"\t"+detalle.getCodContaler()+"\t"+detalle.getCodOperale());
		}
	}*/
}
